<template>
    <div class="content">
        <div>
            <input type="button" value="新增" @click="$router.push('/addBook')" />
            <input type="text" placeholder="请输入关键词" v-model="keyWord" />
            <input type="button" value="查询" @click="query" />
        </div>
        <table>
            <thead>
                <tr>
                    <th>编号</th>
                    <th>图书名称</th>
                    <th>作者</th>
                    <th>价格</th>
                    <th>操作</th>
                </tr>
            </thead>

            <tbody v-if="books && books.length">
                <tr v-for="book in books" :key="book.id">
                    <td>{{ book.id }}</td>
                    <td>{{ book.bookName }}</td>
                    <td>{{ book.autor }}</td>
                    <td>{{ book.price }}</td>
                    <td>
                        <input type="button" value="修改" @click="$router.push(`/updateBook/${book.id}`)" />
                        <input type="button" value="删除" @click="del(book.id)" />
                    </td>
                </tr>
            </tbody>

            <tbody v-else>
                <tr>
                    <td colspan="5">暂无数据</td>
                </tr>
            </tbody>
        </table>
    </div>
</template>

<script setup>
// 引用 api
import { ref, onMounted } from "vue"
import { useRouter } from "vue-router";
import axios from "axios"

// 后端 api
const api = "http://localhost:8000/books"

// 响应数据
const books = ref([])

// 查询关键词
const keyWord = ref('')

// 创建实例
const router = useRouter();

// 查询方法
async function findAll() {
    const data = await axios.get(`${api}?keyWord=${keyWord.value}`)
    books.value = data.data.data
}

// 生命周期方法
onMounted(async () => {
    await findAll();
})

// 查询
async function query() {
    await findAll()
}

// 删除
async function del(id) {
    if (confirm("确认删除？")) {
        const data = await axios.delete(`${api}/${id}`)
        if (data.data.code === 200) {
            const index = books.value.findIndex((item) => item.id === id)
            books.value.splice(index, 1)
        }
    }
}
</script>

<style scoped>
.content div:first-child {
    margin: 10px;
}
</style>